#include "music.h"
#include<QUuid>
#include<QMediaPlayer>
#include<QCoreApplication>
#include<QSqlQuery>
#include<QSqlError>

Music::Music()
    :isLike(false),isHistory(false)
{

}

Music::Music(QUrl url)
    :isLike(false),isHistory(false),musicUrl(url)
{
    musicId=QUuid::createUuid().toString();
    parseMediaMetaMusic();

}

void Music::setMusicId(const QString &musicId)
{
    this->musicId=musicId;
}

void Music::setMusicName(const QString &musicname)
{
    this->musicName=musicname;
}

void Music::setMusicSinger(const QString &musicSinger)
{
    this->musicSinger=musicSinger;
}

void Music::setMusicAlbumn(const QString &musicAlbumn)
{
    this->musicAlbumn=musicAlbumn;
}

void Music::setMusicDuration(qint64 Duration)
{
    this->duration=Duration;
}

void Music::setIsLike(bool isLike)
{
    this->isLike=isLike;
}

void Music::setIsHistory(bool isHistory)
{
    this->isHistory=isHistory;
}

void Music::setMusicUrl(QUrl musicUrl)
{
    this->musicUrl=musicUrl;
}

void Music::setMusicNet()
{
    this->isFromNet=true;
}

QString Music::getMusicName() const
{
    return musicName;
}

QString Music::getMusicSinger() const
{
    return musicSinger;
}

QString Music::getMusicAlbumn() const
{
    return musicAlbumn;
}

qint64 Music::getMusicDuration() const
{
    return duration;
}

bool Music::getIsLike() const
{
    return isLike;
}

bool Music::getIsHistory() const
{
    return isHistory;
}

QUrl Music::getMusicUrl() const
{
    return musicUrl;
}

QString Music::getMusicId() const
{
    return musicId;
}

bool Music::getIsFromNet() const
{
    return this->isFromNet;
}

QString Music::getLrcFilePath()
{
    qDebug()<<"转换前QUrl"<<getMusicName()<<"  "<<getMusicUrl();
    QString lrcPath=musicUrl.toString();
    qDebug()<<"转换后QString"<<lrcPath;
    lrcPath.replace(".mp3",".lrc");
    lrcPath.replace(".flac",".lrc");
    lrcPath.replace(".wav",".lrc");

    return lrcPath;
}

void Music::InsertMusicToDB()
{
    // 1. 检测music是否在数据库中存在
    QSqlQuery query;


    query.prepare("SELECT EXISTS (SELECT 1 FROM MusicInfo WHERE musicId = ?)");
    query.addBindValue(musicId);
    if(!query.exec())
    {
        qDebug()<<"查询失败: "<<query.lastError().text();
        return;
    }

    if(query.next())
    {
        bool isExists = query.value(0).toBool();
        if(isExists)
        {
            // musicId的歌曲已经存在
            // 2. 存在：不需要再插入musci对象，此时只需要将isLike和isHistory属性进行更新
            query.prepare("UPDATE MusicInfo SET isLike = ?, isHistory = ? WHERE musicId = ?");
            query.addBindValue(isLike? 1 : 0);
            query.addBindValue(isHistory? 1 : 0);
            query.addBindValue(musicId);
            if(!query.exec())
            {
                qDebug()<<"更新失败: "<<query.lastError().text();
            }

            qDebug()<<"更新music信息: "<<musicName<<" "<<musicId;
        }
        else
        {
            // 3. 不存在：直接将music的属性信息插入数据库
            query.prepare("INSERT INTO MusicInfo(musicId, musicName, musicSinger, albumName, musicUrl,\
                          duration, isLike, isHistory)\
                    VALUES(?,?,?,?,?,?,?,?)");
            query.addBindValue(musicId);
            query.addBindValue(musicName);
            query.addBindValue(musicSinger);
            query.addBindValue(musicAlbumn);
            query.addBindValue(musicUrl.toLocalFile());
            query.addBindValue(duration);
            query.addBindValue(isLike ? 1 : 0);
            query.addBindValue(isHistory? 1 : 0);

            if(!query.exec())
            {
                qDebug()<<"插入失败: "<<query.lastError().text();
                return;
            }

            qDebug()<<"插入music信息: "<<musicName<<" "<<musicId;
        }
    }

}

void Music::parseMediaMetaMusic()
{
    QMediaPlayer player;

    player.setMedia(musicUrl);
    qDebug()<<"setMedia()";

    while(!player.isMetaDataAvailable()){
        QCoreApplication::processEvents();
    }

    if(player.isMetaDataAvailable()){
        musicName = player.metaData("Title").toString();
        musicAlbumn=player.metaData("AlbumTitle").toString();
        musicSinger=player.metaData("Author").toString();
        duration=player.metaData("Duration").toLongLong();

        if(musicName.isEmpty()){
            QString filename=musicUrl.fileName();

            int pos=filename.indexOf('-');
            if(pos!=-1){
                musicName=filename.mid(0,pos);
            }
            else{
                int pos=filename.indexOf('.');
                musicName=filename.mid(0,pos);
            }
        }

        if(musicSinger.isEmpty()){
            musicSinger="未知歌手";
        }
        if(musicAlbumn.isEmpty()){
            musicAlbumn="未知专辑";
        }
        qDebug()<<musicName<<"  "<<musicAlbumn<<"  "<<musicSinger<<"  "<<duration;
    }

}
